package com.ly.mpayment.rest.up.jiamiduo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import com.ly.mpayment.rest.up.util.Util;
import org.apache.log4j.Logger;
import org.mortbay.util.MultiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
@Path("jiamiduo")
public class JiaMiDuoRest {
    Logger logger = Logger.getLogger(JiaMiDuoRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    @Path("callBack")
    @POST
    public String callBack(@RequestBody String data) {
        logger.info("jiamiduo_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            JSONObject json = JSONObject.parseObject(data);

            UpOrder order = upOrderService.findById(json.getString("tradeNo"));
            if(order == null){
                logger.info("orderNotify_not_found_order:"+json.getString("tradeNo"));
            }
            if(json.getString("shipping_status").equals("1") && order != null  && order.getStatus() == Config.status[0]){
                order.setRemark(json.containsKey("vouchertype") ? json.getString("vouchertype") : json.getString("shipping_status"));
                RechargeRest.successUpOrder.add(order);
            }else if(order != null  && order.getStatus() == Config.status[0] && (
                    json.getString("shipping_status").equals("0") || json.getString("shipping_status").equals("4")
            )){
                order.setRemark(json.getString("shipping_status_message"));
                RechargeRest.failtUpOrder.add(order);
            }
            return Config.success;
        }
        return "0";
    }


    /**
     * 订单提交
     *
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        UpOrder product = upOrderService.findOrderProduct(order.getUporderuuid());
        if (product != null) {
            JSONObject sb = new JSONObject();
            sb.put("phone",order.getUpphonenum());
            sb.put("product_id",product.getUpShopPro().getProductCode());
            sb.put("notify_url",shop.getOrderStatusAddress());
            sb.put("tradeNo",order.getUporderuuid());
            long ts = DateUtils.getNowDate().getTime() / 1000;
            Map<String, String> headers = MapUtil.getMapString();
            headers.put("API-USER-NAME",shop.getAppId() );
            headers.put("API-NAME","OrderCreate" );
            headers.put("API-TIMESTAMP",ts+"" );
            //String API-SIGNATURE = md5(API-IP+API-TIMESTAMP+API-CERT);
            headers.put("API-SIGNATURE",MD5.md5(shop.getUpshopip()+ts+shop.getUpkey()) );
//		{
//		    "ack": "success",   //下单成功是success，下单失败是failure
//		    "message": "",
//		    "order_number": "LLW41.....",
//		    "charge_amount": "1.00",
//		    "shipping_status": 1,
//		    "shipping_status_desc": "未充值",
//		    "custom_number": "",
//		    "serial_number": "LLW41.....",
//		}
            String result = HttpClient.post10086Json(shop.getOrderCommitAddress(), sb.toString(),headers);
            logger.info("commitjiamiduo:"+result);
            if(!StringUtils.isBlank(result)){
               net.sf.json.JSONObject json = JsonUtils.getJSONOBJCT().fromObject(result);
                if(json.containsKey("ack") && json.getString("ack").equals(Config.success)){
                    upOrderService.updateUpOrderMsg(order, json.getJSONObject("message").containsKey("order_number") ? json.getJSONObject("message").getString("order_number") : "",json.getString("ack"));
                }else if(json.containsKey("ack") && json.getString("ack").equals("failure")){
                    order.setRemark( json.getString("message"));
                    RechargeRest.failtUpOrder.add(order);
                }
            } else {
                upOrderService.updateUpOrderMsg(order, "","提单失败人工核对:"+result);
            }
        }else{
            logger.info("commitLeXiang error not found product" + order.getUporderuuid());
        }
    }

    /**
     * 订单查询
     *
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        JSONObject data = new JSONObject();
        data.put("tradeNo", upOrder.getUporderuuid());
        long ts = DateUtils.getNowDate().getTime() / 1000;
        Map<String, String> headers = MapUtil.getMapString();
        headers.put("API-USER-NAME",shopInfo.getAppId() );
        headers.put("API-NAME","OrderQuery" );
        headers.put("API-TIMESTAMP",ts+"" );
        headers.put("API-SIGNATURE",MD5.md5(shopInfo.getUpshopip()+ts+shopInfo.getUpkey()));
        String result = HttpClient.post10086Json(shopInfo.getOrderStatusAddress(), data.toString(),headers);
        logger.info("jiamiduo_orderQuery:"+result);
        if(result != null){
            net.sf.json.JSONObject json = JsonUtils.getJSONOBJCT().fromObject(result);
            if(json.containsKey("ack") && json.getString("ack").equals(Config.success)){
                //0 失败，1 成功，4失败
                if(upOrder != null && json.getJSONObject("order").getString("shipping_status").equals("1") && upOrder.getStatus() == Config.status[0]){
                    upOrder.setRemark(json.getJSONObject("order").containsKey("voucher") ?
                            json.getJSONObject("order").getString("voucher") : json.getJSONObject("order").getString("shipping_status_desc"));
                    RechargeRest.successUpOrder.add(upOrder);
                }else if( (json.getJSONObject("order").getString("shipping_status").equals("0") ||
                        json.getJSONObject("order").getString("shipping_status").equals("4")) && upOrder != null && upOrder.getStatus() == Config.status[0]){
                    upOrder.setRemark( json.getJSONObject("order").getString("shipping_status_desc")+","+json.getJSONObject("order").getString("shipping_status_message"));
                    RechargeRest.failtUpOrder.add(upOrder);
                }
            }
        }else{
            logger.info("jiamiduo order failt:"+upOrder.getUpphonenum());
        }
    }
}
